const UserModel = require('../../db/models/user');
const MenuModel = require('../../db/models/menu');

// 获取菜单列表 (按条件查询)
const queryMenuList = async function (ctx, next) {
  const paylod = ctx.state.user;
  const userInfo = await UserModel.find({ _id: paylod._id });
  const roles = userInfo[0].role;
  const params = ctx.request.query;
  const reg = new RegExp(params.name, 'i');
  const menuList = await MenuModel.find({
    role: { $in: roles },
    $or: [{ name: { $regex: reg } }]
  }).sort({ sort: 1 });
  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].parent) {
      let idx = menuList.findIndex((r) => r.key === menuList[i].parent);
      menuList[idx].children.push(menuList[i]);
    }
  }
  let tree = menuList.filter((i) => !i.parent);
  ctx.body = tree;
}

// 添加菜单
const addMenu = async function (ctx, next) {
  const data = ctx.request.body;
  await MenuModel.create(data).then(() => {
    ctx.body = {
      success: true
    };
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    };
  });
}

// 删除菜单
const deleteMenu = async function (ctx, next) {
  const params = ctx.request.query;
  await MenuModel.deleteMany(params).then(() => {
    ctx.body = {
      success: true
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  });
}

// 更新菜单
const updateMenu = async function (ctx, next) {
  const data = ctx.request.body;
  await MenuModel
    .where({ _id: data._id })
    .update(data)
    .then(() => {
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    });
}

// 查询单个菜单信息
const queryOneMenu = async function (ctx, next) {
  const params = ctx.request.query;
  await MenuModel.find(params).then(res => {
    ctx.body = {
      success: true,
      data: res
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  });
}

module.exports = {
  queryMenuList,
  addMenu,
  deleteMenu,
  updateMenu,
  queryOneMenu
}
